// Copyright (c) 2023 Huawei Device Co., Ltd.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef UI_GL_OHOS_NATIVE_IMAGE_H_
#define UI_GL_OHOS_NATIVE_IMAGE_H_

#include <memory>

#include "arkweb/ohos_adapter_ndk/interfaces/graphic_adapter.h"
#include "base/functional/callback.h"
#include "base/memory/ref_counted.h"
#include "frame_available_listener_impl.h"
#include "ui/gl/gl_export.h"

namespace gl {

class GL_EXPORT OhosNativeImage
    : public OHOS::NWeb::OhosNativeImageAdapter,
      public base::RefCountedThreadSafe<OhosNativeImage> {
 public:
  static scoped_refptr<OhosNativeImage> Create(int texture_id);

  OhosNativeImage(const OhosNativeImage&) = delete;
  OhosNativeImage& operator=(const OhosNativeImage&) = delete;
  void SetFrameAvailableCallback(base::RepeatingClosure callback);
  void UpdateNativeImage();
  void GetSurfaceId(uint64_t* surface_id);
  void GetTransformMatrix(float mtx[16]);
  void AttachToGLContext();
  void DetachFromGLContext();
  void ReleaseNativeImage();
  void* AquireOhosNativeWindow();
  void OnFrameAvailableListener() override;

  static scoped_refptr<OhosNativeImage> Create();

  int32_t AcquireNativeWindowBuffer(void** windowBuffer, int* acquireFenceFd);

  int32_t GetNativeBuffer(void* windowBuffer, void** nativeBuffer);

  int32_t ReleaseNativeWindowBuffer(void* windowBuffer, int fenceFd);

  void GetNativeWindowBufferSize(void* windowBuffer,
                                 uint32_t* width,
                                 uint32_t* height);

  void GetTransformMatrixV1(float mtx[16], size_t mtx_size);

 protected:
  explicit OhosNativeImage(
      std::unique_ptr<OHOS::NWeb::NativeImageAdapter> native_image_adapter);

 private:
  friend class base::RefCountedThreadSafe<OhosNativeImage>;
  virtual ~OhosNativeImage();

  std::unique_ptr<OHOS::NWeb::NativeImageAdapter> native_image_adapter_;
  std::shared_ptr<OHOS::NWeb::FrameAvailableListenerImpl> listener_;

  base::RepeatingClosure frame_available_cb_;
};

}  // namespace gl

#endif  // UI_GL_OHOS_NATIVE_IMAGE_H_
